import axios from "axios";
import { Message } from "element-ui";
import router from "../router";

const debug = true;
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL, // 后端API地址
  timeout: 5000,
});

// 请求拦截器：添加Token
service.interceptors.request.use(
  (config) => {
    // 打印请求调试信息
    if (debug) {
      console.groupCollapsed(
        `[请求] ${config.method.toUpperCase()} ${config.url}`
      );
      console.log("请求地址:", config.baseURL + config.url);
      console.log("请求方法:", config.method.toUpperCase());
      console.log("请求参数:", config.params || config.data || "无");
      console.log("请求头:", config.headers);
      console.groupEnd();
    }

    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器：处理错误
service.interceptors.response.use(
  (response) => {
    // 打印成功响应调试信息
    if (debug) {
      console.groupCollapsed(
        `[响应] ${response.config.method.toUpperCase()} ${
          response.config.url
        } (${response.status})`
      );
      console.log("响应状态:", response.status, response.statusText);
      console.log("响应数据:", response.data);
      console.log("响应时间:", new Date().toLocaleTimeString());
      console.groupEnd();
    }
    return response.data;
  },
  (error) => {
    // 未登录或Token过期
    if (error.response && error.response.status === 401) {
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      router.push("/auth/login");
      Message.error("登录已过期，请重新登录");
    } else {
      //  element_ui__WEBPACK_IMPORTED_MODULE_2__.Message.error is not a function
      // Message.error(error.response?.data?.message || "操作失败");
      console.error("响应错误:", error);
      Message.error(error.response?.data?.message || "操作失败");
    }
    return Promise.reject(error);
  }
);

export default service;
